// pages/choucha/choucha.js

const db = wx.cloud.database()
const _ = db.command
// 定义变量
let x1,y1

Page({

  /**
   * 页面的初始数据
   */
  data: {
    BZdata:[], //标注数据
    BZdata_flag:false,//是否获取到标注数据
    BZtype:[], //标注类型
    imgSrc:'', //没有后缀的图片文件地址
    photoType:['.jpg','.jpeg','png'],
    colors: ['red', 'blue', 'yellow', 'green'], // 定义一个颜色数组
    ratio:0,
    drawX:0,
    drawY:0,
    drawHeight:0,
    drawWidth:0,
    SQid:'',
    TotalPath:'',//完整的shenqi_output云存储文件路径
    ShTotalPath:'',//完整的shenqi_output_sh云存储文件路径
    FileName:'',//没有路径的文件名，且没有后续
    yesbackcolor:'#4CAF50',
    nobackcolor:'#4CAF50',
    // yesnobackcolor:'#4CAF50',
    btn_flag:true,
    new_load:true, //刚刚转入审核页面标志
    TxtList:[],//预留文件列表
    bznogood:0,//抽查不合格次数
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    var that = this
    console.log(options)
    //获取云存储的fileID
    let SubPath = decodeURIComponent(options.fileid).split('/')
    let FileNameArr = SubPath[1].split('.')
    that.data.FileName = FileNameArr[0]
    let fileID = 'cloud://cloud1-4gcsxcql7d341258.636c-cloud1-4gcsxcql7d341258-1306724370/'+'shenqi_output_sh/'+that.data.FileName+'.txt'
    //获取BZtype
    let BZtype = wx.getStorageSync('BZtype')
    that.setData({
      BZtype
    });
    //获取标注数据，并写入BZdata数组。考虑有两组以上的标注数据
    that.txtToData(fileID)
  },

  //获取Txt文件的SQid
  GetSQid(fileid){
    return new Promise(function(resolve, reject){
      db.collection('ShenQiData')
      .where({
        fileid,
      })
      .orderBy('createtime','desc')
      .get()
      .then(res=>{
        console.log(res)
        resolve(res.data[0]._id)
      })
      .catch(err=>{
        reject(err)
      })
    })
  },

  //获取标注数据，并写入BZdata数组。考虑有两组以上的标注数据
  txtToData(fileID){
    console.log('进入txtToData',fileID)
    wx.showLoading({
      title: '正在载入',
    })
    var that = this
    wx.cloud.downloadFile({
      fileID,  
      success: res => {
        wx.getFileSystemManager().readFile({
          filePath: res.tempFilePath,
          encoding: 'utf-8',
          success: res => {
            //将标注数据整理为数组BZdata，数组元素也是一个数组，包含[classes，x_ ，y_ ，w_ ,h_]
            // console.log(res.data)
            that.data.TxtContent = res.data;
            const arr = that.data.TxtContent.split('\n');
            // console.log(arr)
            let BZdata = []
            for(let i=0;i<arr.length;i++){
              if(arr[0]!=''){
                let itemdata = arr[i].split(' ')
                BZdata.push(itemdata.map(item => parseFloat(item)))
              }
            }
            console.log(BZdata)
            that.data.BZdata_flag = true
            that.data.BZdata = BZdata
            //获取照片的fileid
            db.collection('ShenQiData')
            .where({
              classes:that.data.TxtContent
            })
            .get()
            .then(res=>{
              console.log(res)
              that.data.fileid = res.data[0].fileid
              that.data.SQid = res.data[0]._id
              //此标注是否已被抽查过
              db.collection('ShenQiData')
              .where({
                _id:that.data.SQid,
                cc_id:_.exists(true)
              })
              .get()
              .then(res=>{
                if(res.data.length == 1){
                  wx.showModal({
                    title: '提示',
                    content: '此标注已抽查',
                    showCancel:false,
                    success (res) {
                      if (res.confirm) {
                        wx.redirectTo({
                          url: '/pages/index/index?name=choucha'
                        })
                      } 
                    }
                  })
                }
              })
              // 获取标注照片
              that.GetPhoto(res.data[0].fileid)
            })
          },

        });
      },
      fail: err => { //找不到标注数据
        console.log(err)
      }
    });
  },

  //获取标注图片
  GetPhoto(fileid){
    var that = this
    wx.cloud.getTempFileURL({
      fileList: [{
        fileID: 'cloud://cloud1-4gcsxcql7d341258.636c-cloud1-4gcsxcql7d341258-1306724370/'+fileid,
        // maxAge: 60 * 60, // one hour
      }]
    }).then(res => {
      console.log(res.fileList[0].tempFileURL)
      that.drawImage(res.fileList[0].tempFileURL)
    }).catch(error => {
      console.log(err)
      wx.hideLoading()
    })
  },

  //把图片绘制到画布上，（drawX，drawY）是图片的左上角坐标，drawWidth，drawHeight 是缩放后图片宽度、高度
  drawImage(imgSrc){
    let that = this
    wx.createSelectorQuery().select('#myCanvas').fields({ node: true, size: true }).exec((res0) => {
      //获取canvas宽高
      const canvas = res0[0].node
      // console.log(canvas)
      let ctx = canvas.getContext('2d');
      const cw = res0[0].width
      const ch = res0[0].height
      // console.log('Canvas逻辑宽度：'+cw, 'Canvas逻辑高度：'+ch)
      // 获取物理/逻辑像素比
      const dpr = wx.getSystemInfoSync().pixelRatio
      // console.log(dpr)
      
      canvas.width = cw * dpr     // 获取宽
      canvas.height = ch * dpr  // 获取高
      // console.log('画布像素宽度'+cw * dpr, '画布像素高度'+ch * dpr)
      //放大像素的间距至dpr倍，如果dpr>1，说明在指定画布面积上物理像素变稀疏了
      ctx.scale(dpr, dpr)
      //获取照片，并按画布比例进行缩放，（drawX，drawY）是图片的左上角坐标，drawWidth，drawHeight 是缩放后图片宽度、高度
      wx.getImageInfo({
        src: imgSrc,
        success: function (res) {
          //获取图片宽高
          let iw = res.width
          let ih = res.height
          // console.log('图片宽度：'+iw, '图片高度：'+ih);
          //开始在画布上画照片
          // 计算绘制位置，保持原始比例
          let ratio = Math.min(cw / iw, ch / ih);
          // console.log(ratio)
          // 图片适配画布显示，关键在于计算图片缩放比例
          let drawWidth = iw * ratio; 
          let drawHeight = ih * ratio;
          // console.log('图片缩放后宽度：'+drawWidth, '图片缩放后高度：'+drawHeight);
          let drawX = (cw - drawWidth) / 2;
          let drawY = (ch - drawHeight) / 2;

          // 到这里就可以直接绘制
          let image = canvas.createImage();//创建iamge实例
          image.src = imgSrc;  // 引入本地图片
          image.onload = function () {
            ctx.drawImage(image, 0,0,iw, ih,drawX, drawY, drawWidth, drawHeight);
            //隐藏载入提示(已在onload()中被调用)
            wx.hideLoading()
            //画框
            that.drawRect(ctx, drawX, drawY, drawWidth, drawHeight, image, canvas)
          }
        },
        fail: function (res) {
          console.error('获取图片信息失败', res);
          wx.showModal({
            title: '提示',
            content: '找不到标注照片',
            showCancel:false,
            success (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index?name=choucha'
                })
              } 
            }
          })
        }
      });
    })
  },

  //画框 classes 0=red 1=blue 2=green
  drawRect(ctx, drawX, drawY, drawWidth, drawHeight, image, canvas){
    var that = this
    let BZdata = that.data.BZdata
    //通过遍历的方式获取数组长度
    // const Length = Object.keys(BZdata).filter(key => typeof BZdata[key] !== 'function').length
    // console.log(Length)
    for(let i=0;i<BZdata.length;i++){
      if(BZdata[i]){        
        if(BZdata[i][0]==0){
          ctx.strokeStyle = 'red'
        }else if(BZdata[i][0]==1){
          ctx.strokeStyle = 'blue'
        }else if(BZdata[i][0]==2){
          ctx.strokeStyle = 'yellow'
        }
        
        x1 = drawX + drawWidth*(BZdata[i][1]-0.5*BZdata[i][3])
        y1 = drawY + drawHeight*(BZdata[i][2]-0.5*BZdata[i][4])
        ctx.strokeRect(x1, y1, BZdata[i][3]*drawWidth, BZdata[i][4]*drawHeight)
        ctx.stroke() 
      }
    }
    //重置按钮有效
    that.data.btn_flag = true
    that.setData({
      yesbackcolor:'#4CAF50',
      nobackcolor:'#4CAF50',
      // yesnobackcolor:'#4CAF50',
    })
  },

  //合格
  pass(){
    var that = this
    if(that.data.btn_flag){
      wx.showModal({
        title: '提示',
        content: '该标注“合格”？',
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            that.data.btn_flag = false
            that.setData({
              yesbackcolor:'lightgrey',
              nobackcolor:'grey',
              // yesnobackcolor:'grey'
            })
            wx.showLoading({
              title: '提交中',
            })
            // ShenQiData：增加抽查人字段
            db.collection('ShenQiData')
            .doc(that.data.SQid)
            .update({
              data:{
                cc_id:wx.getStorageSync('myid')
              }
            })
            .then(res=>{
              console.log(res)
              wx.redirectTo({
                url: '/pages/index/index?name=choucha',
              })
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },

  //不合格
  nopass(){
    var that = this
    if(that.data.btn_flag){
      wx.showModal({
        title: '提示',
        content: '该标注“不合格”？',
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            that.data.btn_flag = false
            that.setData({
              yesbackcolor:'grey',
              nobackcolor:'lightgrey',
              // yesnobackcolor:'grey'
            })
            wx.showLoading({
              title: '操作中',
            })
            // ShenQiData：增加抽查人字段
            db.collection('ShenQiData')
            .doc(that.data.SQid)
            .update({
              data:{
                cc_id:wx.getStorageSync('myid')
              }
            })
            .then(res=>{
              console.log(res)
              //审核人bznogood+1
              db.collection('ShenQiData')
              .doc(that.data.SQid)
              .get()
              .then(res=>{
                console.log(res)
                db.collection('userinfo')
                .where({
                  _openid:res.data.sh_id
                })
                .get()
                .then(res=>{
                  if(res.data[0].bznogood == undefined){
                    that.data.bznogood = 0
                  }else{
                    that.data.bznogood = res.data[0].bznogood
                  }
                  db.collection('userinfo')
                  .where({
                    _openid:res.data[0].sh_id
                  })
                  .update({
                    data:{
                      bznogood:that.data.bznogood+1
                    }
                  })
                  .then(res=>{
                    console.log(res)
                    wx.redirectTo({
                      url: '/pages/index/index?name=choucha',
                    })
                  })
                })
              })
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})